package model

import (
	"log"
	"strconv"
	"time"

	"github.com/bear/wolf/config"
	"github.com/bear/wolf/request"
	"gorm.io/gorm"
)

type Project struct{
	Id 			int 	 	`json:"id"`
	ProjectName string   	`json:"projectname"`
	BeginAt 	time.Time 	`gorm:"column:begin_at;type:date" json:"beginAt"`
	EndAt 		time.Time	`gorm:"column:end_at;type:date"  json:"endAt"`
	CreateAt	time.Time 	`gorm:"column:create_at" json:"createAt"`
	UpdateAt 	time.Time 	`gorm:"column:update_at" json:"updateAt"`
}
// 自定义表名
func (p *Project) TableName() string {
	return "project"
}
func (p *Project) BeforeCreate(tx *gorm.DB) error {
    p.CreateAt = time.Now()
    p.UpdateAt = time.Now()
    return nil
}
func (p *Project) BeforeUpdate(tx *gorm.DB) error {
 
    p.UpdateAt = time.Now()
    return nil
}
func CreateProject(p *Project) error{
	
	return config.DB.Create(p).Error
}

//教研username 是否存在
func GetProejctName(projectname string) (*Project,error){
	var project Project
	result := config.DB.Where("project_name = ?",projectname).First(&project)
	// utils.Print2Json(user)
	if result.Error !=nil{
		return nil,result.Error
	}
	return &project,nil
}
//删除 
func DeleteProjectByid(id int) error{
	result := config.DB.Where("id = ?",id).Delete(&Project{})
	return result.Error
}
func UpdateByid(p *Project) error{
	result := config.DB.Where("id=?",p.Id).Updates(p)
	return result.Error
}
//count查询
func GetIdExist(id int) int64{
	var count int64;
	tx := config.DB.Table("project").Where("id=?",id).Count(&count)
	   // 打印调试信息
    log.Printf("检查ID=%d是否存在，SQL: %v，结果: %d条，错误: %v", 
        id, tx.Statement.SQL.String(), count, tx.Error)
	return count ;
}

func GetProjectById(id string) *Project{
	int_id, _ := strconv.Atoi(id)
	var project Project
	config.DB.Table("project").Where("id=?",int_id).First(&project)
	return &project
}

func GetProjectList(req request.ProjectReq) []Project{

	query := config.DB.Table("project");
	if req.ProjectName !=""{
		query.Where("project_name LIke ?", "%" + req.ProjectName + "%")
	}
	if req.BeginAt !=""{
		query.Where("begin_at > ?", req.BeginAt)
	}
	if req.EndAt !=""{
		query.Where("end_at > ?", req.EndAt)
	}
	// 添加排序条件
	query = query.Order("create_at desc")

		// 定义存储查询结果的切片
	var projectList [] Project

	// 执行查询
	query.Find(&projectList)
	return projectList
}

func GetProjectNameById(productId int)string{
	var project Project
	config.DB.Where("id = ?",productId).First(&project)
	log.Printf(project.ProjectName)
	return project.ProjectName
}